<?php
class Routing{
	private $uri;
	private $loader;
	
	public function __construct($loader){
		$this->loader = $loader;
		try{
			if(preg_match('/^[a-z0-9A-Z\- \/]*$/',$_GET["q"])){
				$this->uri = strip_tags($_GET["q"]);
				if ($_GET['q'] === NULL) $this->uri = '/';
			}
			else throw new Exception('nem illeszkedik');
		}
		catch(Exception $e){
			//echo '<b>Hiba: </b>'.$e->getMessage().'<br />';
			Routing::redirect('?q=error/error404');
		}
	}		
	
	public function run(){
		if($this->uri === '/'){
			$t = array();
			$controller_name = 'default';
			$action_name = 'index';
		}
		else{
			$t = explode('/', $this->uri);
			if($t[count($t)-1]=='dev'){}
			if($_SERVER['HTTP_HOST']=='localhost'){
				$controller_name = array_shift($t);
				$action_name = array_shift($t);
			}
			else{
				$controller_name = $t[0];
				$action_name = $t[1];
				for($i=2; $i<(count($t)); $i++){
					$temp[$i-2]=$t[$i];
				}
				$t=$temp;
			}
			if ($action_name === NULL)  {$action_name = 'index';}
		}
		try{		
			$controller = $this->loader->controller($controller_name);
			$function = method_exists ($controller, $action_name);
			$class = class_exists($controller_name.'controller');
			if($function && $class){
				call_user_func_array(array($controller, $action_name), $t);
				$controller->postExecute($action_name);
			}
			else{
				Routing::redirect('?q=error/error404') ;
			}
		}
		catch(Exception $e){
			echo '<b>Hiba: </b>'.$e->getMessage().'<br />';
		}
	}
		
	static public function redirect($path){
		if($_SERVER['HTTP_HOST']=='localhost'){	
			$t = explode('/', $_SERVER['REQUEST_URI']);
			if($_SERVER['HTTPS'] == 'on'){
				$temp = 'https://';
			}	
			else{ 
				$temp = 'http://';
			}
			$temp .= $_SERVER['HTTP_HOST'].'/'.$t[1].$path;
			header('HTTP/1.1 301 Moved Permanently');
			header('Location: '.$temp);
			exit(0);
			return $temp;
		}
		else{
			$t = explode('/', $_SERVER['REQUEST_URI']);
			if($_SERVER['HTTPS'] == 'on'){
				$temp = 'https://';
			}
			else{ 
				$temp = 'http://';
			}	
			$temp .= $_SERVER['HTTP_HOST'].'/'.$t[0].$path;
			header('HTTP/1.1 301 Moved Permanently');
			header('Location: '.$temp);
			exit(0);
			return $temp;
		}
	}
}